package com.hkbigdata.wordcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author liuanbo
 * @creat 2023-03-22-17:20
 * @see 2194550857@qq.com
 */
public class Flink01_WordCount_Batch {
    public static void main(String[] args) throws Exception {
        //1.创建环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //2.读取数据源
        DataSource<String> source = env.readTextFile("input/word.txt");

        //3.扁平化
        FlatMapOperator<String, String> word = source.flatMap(new MyFlatMapFunction());

        //4.转换为元祖（hello，1）
        MapOperator<String, Tuple2<String, Integer>> wordtoone = word.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return new Tuple2<>(value, 1);
            }
        });

        //5.分组
        UnsortedGrouping<Tuple2<String, Integer>> tuple2UnsortedGrouping = wordtoone.groupBy(0);

        //6.聚合
        AggregateOperator<Tuple2<String, Integer>> sum = tuple2UnsortedGrouping.sum(1);

        sum.print();

        env.execute();


    }

    public static class MyFlatMapFunction implements FlatMapFunction<String,String>{

        @Override
        public void flatMap(String value, Collector<String> out) throws Exception {
            String[] words = value.split(" ");

            for (String word : words) {
                out.collect(word);
            }

        }
    }
}
